import math
from datetime import datetime

from bs4 import BeautifulSoup
from config import liuyao_config
import pandas as pd
from config.excel_config import column_name
from h3yun.service import medical_goods_servce, site_data_service, goods_service
from logs.set_logfile import logger
from utils import clean_utils
from clean_data.common.common import get_site_dict
from utils.clean_utils import is_empty
from config.h3yun_config import pss_site_mate_tableName, pss_goods_mate_tableName
from clean_data.common.common import get_pss_site_to_h3yun_site_dict, get_pss_goods_to_h3yun_site_dict

# get_goods_code 获取柳药导出数据的商品编码
# get_c  C 通用名 -> I2 配送商备案产品
# get_i  I 销售数量 -> U2 数量
# get_k  K 客户名称 -> L2 医院名称
# get_l_and_p  l 制单日期 -> C2 出库时间
#              P 批号 -> AD2 批次信息


# 广西柳药集团股份有限公司 站点编码 02093001
# 广州天宝颂原生物科技开发有限公司 站点编码 01045001
def create_soup():
    html_file_path = liuyao_config.liuyao_goods_html_url
    # html_file_path = "D:\\scraping\\pythonProject\\download_selenium_excel_file\\2024-01-25\\柳药商品流向.html"
    # 打开并读取 HTML 文件
    with open(html_file_path, 'r', encoding='utf-8') as file:
        html_content = file.read()
    # 使用 BeautifulSoup 解析 HTML
    soup = BeautifulSoup(html_content, 'html.parser')
    return soup


exception_msg = []

# 商品编码
def get_goods_code(soup):
    # 获取 id 为 table_id 的 table 标签
    table = soup.find('table', id='report1')
    first_td_texts = []
    if table:
        # 提取 table 标签内的所有 tr 标签
        tr_tags = table.find_all('tr')
        for tr in tr_tags:
            # 获取 tr 标签下的第一个 class 名字为 class_name 的 td 标签
            first_td = tr.find('td', class_='report1_4_1')
            if first_td:
                # 获取第一个 td 标签的文本内容
                first_td_texts.append(first_td.get_text(strip=True))
    return first_td_texts


# 产品名称
# F0000008 产品名称（公司内部的）
# F0000003 产品编码（公司内部的）

# 同时匹配产品编码和产品名称
def get_c(goods_code_column):
    goods_code_dict = get_goods_code_dict()
    c = []
    temp = []
    global exception_msg
    index = 0
    for code in goods_code_column:
        if is_empty(goods_code_dict.get(code)):
            exception_msg[index] += f'{pss_goods_mate_tableName} 没有产品编码(配送商) "{code}" 的产品;'
            c.append('')
            temp.append('')
        else:
            c.append(goods_code_dict[code]['F0000003'])
            temp.append(goods_code_dict[code]['F0000004'])
        index += 1
    return c, temp


# 配送商的产品名称
def get_PSS_CPMC(soup):
    report1_4_3 = soup.find_all('td', class_='report1_4_3')
    C = [item.text for item in report1_4_3]
    return C
# 通用名I2
# def get_c(soup):
#     report1_4_3 = soup.find_all('td', class_='report1_4_3')
#    # print('通用名I2')
#     C = []
#     for item in report1_4_3:
#         text = item.text
#         if item.text == 'D-二聚体测定试剂盒(荧光免疫层析法)':
#             text = 'D—二聚体测定试剂盒(荧光免疫层析法)'
#
#         elif item.text == '心肌肌钙蛋白I/肌红蛋白/肌酸激酶同工酶联合测定试剂?':
#             text = '心肌肌钙蛋白I/肌红蛋白/肌酸激酶同工酶联合测定试剂盒（荧光免疫层析法）'
#
#         elif item.text == '心肌肌钙蛋白I/脑钠肽/D-二聚体联合测定试剂盒(荧光免':
#             text = '心肌肌钙蛋白I/脑钠肽/D—二聚体联合测定试剂盒（荧光免疫层析法）'
#
#         elif item.text == '心肌肌钙蛋白I测定试剂盒(荧光免疫层析法）':
#             text = '心肌肌钙蛋白I测定试剂盒(荧光免疫层析法)'
#
#         elif item.text == 'D-二聚体检测试剂盒(荧光免疫层析法)':
#             text = 'D—二聚体检测试剂盒(荧光免疫层析法)'
#
#         elif item.text == '心肌肌钙蛋白I/肌红蛋白/肌酸激酶同工酶联合测定试剂盒(荧光免疫 层析法)':
#             text = '心肌肌钙蛋白I/肌红蛋白/肌酸激酶同工酶联合测定试剂盒（荧光免疫层析法）'
#
#         elif item.text == '心肌肌钙蛋白I/脑钠肽/D-二聚体联合测定试剂盒(荧光免疫层析法)':
#             text = '心肌肌钙蛋白I/脑钠肽/D—二聚体联合测定试剂盒（荧光免疫层析法）'
#         C.append(text)
#     return C


# 销售数量U2
def get_i(soup):
    # print('销售数量U2')
    I = []
    report1_4_9 = soup.find_all('td', class_='report1_4_9')
    for item in report1_4_9:
        I.append(item.text)
    # print(I)
    return I


# 客户名称 以及 客户名称编码（公司内部的）客户名称编码（配送商的）
def get_k(soup):
    # 获取 id 为 table_id 的 table 标签
    table = soup.find('table', id='report1')
    first_td_texts = []
    if table:
        # 提取 table 标签内的所有 tr 标签
        tr_tags = table.find_all('tr')
        for tr in tr_tags:
            # 获取 tr 标签下的第一个 class 名字为 class_name 的 td 标签
            first_td = tr.find('td', class_='report1_4_10')
            if first_td:
                # 获取第一个 td 标签的文本内容
                first_td_texts.append(first_td.get_text(strip=True))
    customer_code_dict = get_customer_code_dict()
    # temp1 = []  # 客户名称
    # temp2 = []  # 客户名称编码（公司内部的）
    # index = 0
    # for first_td in first_td_texts:
    #     if is_empty(customer_code_dict.get(first_td)):
    #         exception_msg[index] += f'{pss_site_mate_tableName} 没有客户编码(配送商) "{first_td}"的产品;'
    #         temp1.append('')
    #         temp2.append('')
    #     else:
    #         temp1.append(customer_code_dict[first_td]['F0000003'])
    #         temp2.append(customer_code_dict[first_td]['F0000004'])
    #     index += 1
    temp1 = ['' for _ in first_td_texts]  # 客户名称
    temp2 = ['' for _ in first_td_texts]  # 客户名称编码（公司内部的）
    return temp1, first_td_texts,  temp2


# 客户名称L2
def get_KHMC_pss(soup):
    K = []
    report1_tables = soup.find_all('table', id='report1')
    for table in report1_tables:
        tr_elements = table.find_all('tr')
        for tr in tr_elements:
            td_elements_with_class = tr.select('td[class="report1_4_4"]')
            # 这个是规格
            # str(td_elements_with_class[2])
            if len(td_elements_with_class) == 4:
                text = td_elements_with_class[2].text
                K.append(text)
    return K


# 制单日期C2 批号AD2
def get_l_and_p(soup):
    #print("制单日期C2 批号AD2")
    L = []
    P = []
    report1_tables = soup.find_all('table', id='report1')
    # 遍历每个 table 标签
    for table in report1_tables:
        # 查找当前 table 标签下的所有 tr 标签
        tr_elements = table.find_all('tr')
        # 遍历每个 tr 标签
        count = 1
        for tr in tr_elements:
            # 查找当前 tr 标签下的所有 td 标签，仅包含 class 属性而没有其他属性
            td_elements_with_class = tr.select('td[class="report1_4_1"]')
            if len(td_elements_with_class) <= 6:
                continue
            e5 = td_elements_with_class[len(td_elements_with_class)-3]
            e8 = td_elements_with_class[len(td_elements_with_class)-1]
            L.append(e5.text)
            P.append(e8.text)
    #print(L)
    #print(P)
    return [L, P]


def get_LHXX(soup):
    # print('销售数量U2')
    LHXX = []
    report1_tables = soup.find_all('table', id='report1')
    # 遍历每个 table 标签
    for table in report1_tables:
        # 查找当前 table 标签下的所有 tr 标签
        tr_elements = table.find_all('tr')

        for tr in tr_elements:
            # 查找当前 tr 标签下的所有 td 标签，仅包含 class 属性而没有其他属性
            td_elements_with_class = tr.select('td[class="report1_4_17"]')
            if len(td_elements_with_class) < 8:
                continue
            LHXX.append(td_elements_with_class[5].text.strip())
    return LHXX


# 检查是不是空
def check_empty(soup):
    td_elements_with_class = soup.find_all('td', class_='report1_4_9')
    for td in td_elements_with_class:
        if len(str(td.text)) == 0 or td.text == 0:
            return True
    return False


def clean_data():
    soup = create_soup()
    global exception_msg
    ID = []
    C = []
    I = []
    K = []
    KHBM_GSNB = []
    KHBM_PSS = []
    L = []
    P = []
    CPBM_PSS = []
    CPBM_GSNB = []
    res = check_empty(soup)
    if not res:
        CPBM_PSS = get_goods_code(soup)
        exception_msg = ['' for _ in CPBM_PSS]
        # C, CPBM_GSNB = get_c(CPBM_PSS)
        C, CPBM_GSNB = ['' for _ in CPBM_PSS], ['' for _ in CPBM_PSS]
        I = get_i(soup)
        K, KHBM_PSS, KHBM_GSNB = get_k(soup)
        temp = get_l_and_p(soup)
        L = temp[0]
        P = temp[1]
        ID = clean_utils.get_ids(liuyao_config.id_prefix, L)

    data = {
        # '商品编码': goods_code_column,
        column_name['ID']: ID,
        column_name['CKSJ']: L,
        column_name['PSS']: ["广西柳药集团股份有限公司"] * len(C),
        column_name['CPMC_PSS']: get_PSS_CPMC(soup),
        column_name['CPMC_GSNB']: C,
        column_name['CPBM_PSS']: CPBM_PSS,
        column_name['CPBM_GSNB']: CPBM_GSNB,
        # column_name['SCCJ']:  ["广州天宝颂原生物科技开发有限公司"] * len(C),
        column_name['KHMC_PSS']: get_KHMC_pss(soup),
        column_name['YYMC_GSNB']: K,
        column_name['KHBM']: KHBM_PSS,
        column_name['YYBM']: KHBM_GSNB,
        column_name['SL']: I,
        column_name['DJ']: [''] * len(C),
        column_name['PCXX']: P,
        column_name['DJ']: [''] * len(C),
        column_name['SCCJ']: [''] * len(C),
        column_name['LHXX']: get_LHXX(soup),
        column_name['YC']: [''] * len(C),
        column_name['SJLY']: [liuyao_config.data_source]*len(C),
    }

    # 检查是否为空 因为柳药导出来的数据 为空也会多一行出来
    if len(data[column_name['CKSJ']]) == 0:
        for key in data.keys():
            data[key] = []

    # # 先匹配备案表
    # goods_list = get_medical_goods_dict()
    # price, sccj = mate_price(goods_list, KHBM_GSNB, CPBM_GSNB)
    #
    # # 在匹配产品销售备案变更备案表
    # medical_change_goods_list = get_change_medical_goods_list()
    # price, sccj = mate_change_price(price, sccj, medical_change_goods_list, KHBM_GSNB, L, CPBM_GSNB)

    # data[column_name['DJ']] = price
    # data[column_name['SCCJ']] = sccj
    # data[column_name['YC']] = exception_msg

    df = pd.DataFrame(data)
    df.to_excel(liuyao_config.excel_file_url, index=False)


def get_medical_goods_dict():
    # 这个matchers应该是没有用的
    matchers = [
        {
            "Type": "And",
            "Matchers": [
                {
                    "Type": "Item",
                    "Name": "F0000049",
                    "Operator": 8,
                    "Value": "02093001"
                },
            ]
        }
    ]
    goods_list = medical_goods_servce.find_medical_goods_data(matchers)
    return goods_list


# 因为导出来的excel没有单价需要去氚云上面匹配，但是价格是会变化的，所以要以备案表的为准
def get_change_medical_goods_list():
    temp = medical_goods_servce.find_medical_changes_goods_data()
    temp_list = []
    for t in temp:
        if t['Status'] == 1 and t['F0000049'] == '02093001':
            temp_list.append(t)
    return temp_list


# F0000002 产品编码
def get_goods_code_dict():
    goods_code_dict = get_pss_goods_to_h3yun_site_dict('02093001')
    return goods_code_dict


# F0000004 客户编码(配送商的)
def get_customer_code_dict():
    customer_code_dict = get_pss_site_to_h3yun_site_dict('02093001')
    return customer_code_dict


#  根据  厂家+产品+医院
#  good_list : 氚云上面返回的产品备案列表
#  site_dict : 站点名称 所对应的 编码
#  yymc: 柳药网站导出来的医院名称那一列
#  BACP: 备案产品名称
# 广西柳药集团股份有限公司 站点编码 02093001
# 广州天宝颂原生物科技开发有限公司 站点编码 01045001
#  F0000049 备案销售客户/医院名称编码
#  F0000051 销售终端医院编码
# D117400Fnczoagqa7nmbvn0erffeps704.F0000026 产品编码
# D117400Fnczoagqa7nmbvn0erffeps704.F0000023 生产厂家名称
# D117400Fnczoagqa7nmbvn0erffeps704.F0000045 终端医院供货价
# D117400Fnczoagqa7nmbvn0erffeps704.F0000006 产品名称
def mate_price(goods_list, YYPM, CPBM):
    price = ['']*len(YYPM)
    sccj = ['']*len(YYPM)
    for i in range(len(YYPM)):
        yymc_code = YYPM[i]
        flag = 0
        for goods in goods_list:
            if goods['F0000049'] == '02093001' and goods['F0000051'] == yymc_code:
                medical_goods_list = goods['D117400Fnczoagqa7nmbvn0erffeps704']
                for medical_goods in medical_goods_list:
                    if medical_goods['F0000026'] == CPBM[i]:
                        # price.append()
                        price[i] = medical_goods['F0000045']
                        sccj[i] = medical_goods['F0000023']
                       # print(i, medical_goods['F0000006'], medical_goods['F0000045'])
                        flag = 1
                        break
            if flag == 1:
                break
    for i in range(len(price)):
        if len(price) == 0:
            logger.error(f'{YYPM[i]} {CPBM[i]} 价格匹配失败')
    return price, sccj


# F0000049 销售客户名称/医院编码
# F0000051 销售终端医院编码
#  D117400Fbslm7kwhysem74i3jdcu3zl47.F0000078 变更后-执行日期
# D117400Fbslm7kwhysem74i3jdcu3zl47.F0000026 产品编号
# D117400Fbslm7kwhysem74i3jdcu3zl47.F0000008 公司销售单价（元）
# D117400Fbslm7kwhysem74i3jdcu3zl47.F0000069 变更后终端医院供货价
# 在对比一下医疗器械销售信息备案-变更
def mate_change_price(price, sccj, medical_goods_list, YYBM, CKSJ, BACP):

    for i in range(len(YYBM)):
        yymc_code = YYBM[i]
        price_change_list = []
        for medical_goods in medical_goods_list:
            if medical_goods['F0000049'] == '02093001' and medical_goods['F0000051'] == yymc_code:
                goods_list = medical_goods['D117400Fbslm7kwhysem74i3jdcu3zl47']
                for goods in goods_list:
                    # 原始日期字符串
                    date_str = goods['F0000078']
                    # 解析原始日期字符串
                    date_obj = datetime.strptime(date_str, "%Y/%m/%d %H:%M:%S")
                    # 转换为所需格式
                    new_date_str = date_obj.strftime("%Y-%m-%d")
                    if goods['F0000026'] == BACP[i] and new_date_str <= CKSJ[i]:
                        price_change_list.append({
                            'date': new_date_str,
                            'price': goods['F0000069']
                        })
        if len(price_change_list) != 0:
            sorted_PSD_list = sorted(price_change_list, key=lambda x: x['date'], reverse=True)
            price[i] = sorted_PSD_list[0]['price']

    return price, sccj


if __name__ == '__main__':
   # clean_data()
   soup = create_soup()
   print(get_LHXX(soup))
   # print(get_goods_code(soup))
   # print(len(get_goods_code(soup)))
   # print(len(get_c(soup)))
